package com.lei.study.mvel.basic;

import org.junit.Test;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.MapVariableResolverFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author 伍磊
 */
public class Expression {

    private Map<String, Object> map = new HashMap<>(16);

    /**
     * 布尔表达式
     */
    @Test
    public void test() {
        map.put("a", 20);
        System.out.println(MVEL.eval("a > 20", map));
    }

    /**
     * 复合表达式
     * ";"
     */
    @Test
    public void test1() {
        String expression = "a = a + 1; a++; a = a * 8";
        map.put("a", 1);
        System.out.println(MVEL.eval(expression, map));
    }

    /**
     * MVEL返回值
     * 输出最后值原则
     */
    @Test
    public void test2() {
        String expression = "a = a + 1; a++; a = a * 8; a";
        map.put("a", 1);
        System.out.println(MVEL.eval(expression, map));
    }

    /**
     * 操作符
     */
    @Test
    public void test3() {
        String expression = "new com.lei.study.mvel.basic.User('伍磊', 2)";
        System.out.println(MVEL.eval(expression));
    }

    /**
     * map
     */
    @Test
    public void test4() {
        String expression = "['lei':new com.lei.study.mvel.basic.User('伍磊', 1)" +
                ", 'x': new com.lei.study.mvel.basic.User('X', 2)]";
        Map map = (Map) MVEL.eval(expression);
        System.out.println(map.get("lei"));
    }

    /**
     * 属性访问
     */
    @Test
    public void test5() {
        User user = new User("伍磊", 1);
        map.put("user1", user);
        String expression = "user?";

        System.out.println(MVEL.eval(expression, map));
    }

    /**
     * 投影
     */
    @Test
    public void test6() {
        User u1 = new User("伍磊1", 1);
        User u2 = new User("伍磊2", 11);
        User u3 = new User("3", 12);
        List<User> list = new ArrayList<>();
        list.add(u1);
        list.add(u2);
        list.add(u3);

        map.put("list", list);
        System.out.println(MVEL.eval("user in list if user.name contains '伍磊'", map));

    }

    @Test
    public void test7() throws IOException {
        File file = new File("/Users/wulei/code-personal/mvel/mvel-study/src/main/java/com/lei/study/mvel/basic/test.el");
        VariableResolverFactory resolverFactory = new MapVariableResolverFactory();
        map.put("a", 11);
        map.put("b", 12);

        System.out.println(MVEL.evalFile(file, ParserContext.create(), map));
    }
  }
